package com.comcast.util;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ConfigurableApplicationContext;
import com.comcast.util.AppContextSingletonBeanFactoryLocator;

public final class ObjectFactory {

    //The name of the root spring configuration file
    private static final String BEAN_FACTORY_LOCATOR_KEY = "application-context";
    private static Object o = new Object();
    
    private ObjectFactory() {}
    
    public static void setSpringContextResourceLocation(String beanRefContext) {
    	AppContextSingletonBeanFactoryLocator.setResourceLocation(beanRefContext);    	
    }
    
    
    public static Object getBean(String name) {
    	ConfigurableApplicationContext context = (ConfigurableApplicationContext)getFactory();
    	if ( !context.isActive() ) {
    		//Reload spring configurations if context is closed when the application
    		//is stopped.
    		context.refresh();
    	}
        return context.getBean(name);
    }
    
    public static void destroy() {
        try {
            ConfigurableApplicationContext context = (ConfigurableApplicationContext)getFactory();
            getReference().release();
            context.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static BeanFactory getFactory() {
        return getReference().getFactory();
    }    

    private static BeanFactoryReference getReference() {
    	BeanFactoryLocator bfl = AppContextSingletonBeanFactoryLocator.getAppInstance(o);
    	return bfl.useBeanFactory(BEAN_FACTORY_LOCATOR_KEY);
    }
}
